using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace axCommerce.Data
{
	[DataObject]
	[Serializable]
	public partial class Permission
	{
		#region Constants

		private const string TableName = "[dbo].[Permission]";

		#endregion

		#region Properties

		public int? PermissionId { get; set; }
		public int? AccountId { get; set; }
		public int? AccessRoleId { get; set; }
		public DateTime? CreatedDate { get; set; }
		public DateTime? LastModifiedDate { get; set; }
		public bool? IsDeleted { get; set; }

		#endregion

		#region Methods

		#region Mapping Methods

		protected void MapTo(DataSet ds)
		{
			if (ds == null)
				ds = new DataSet();

			if (ds.Tables[TableName] == null)
				ds.Tables.Add(TableName);

			ds.Tables[TableName].Columns.Add("PermissionId", typeof (Int32));
			ds.Tables[TableName].Columns.Add("AccountId", typeof (Int32));
			ds.Tables[TableName].Columns.Add("AccessRoleId", typeof (Int32));
			ds.Tables[TableName].Columns.Add("CreatedDate", typeof (DateTime));
			ds.Tables[TableName].Columns.Add("LastModifiedDate", typeof (DateTime));
			ds.Tables[TableName].Columns.Add("IsDeleted", typeof(Boolean));

			DataRow dr = ds.Tables[TableName].NewRow();

			dr["PermissionId"] = PermissionId ?? (object) DBNull.Value;
			dr["AccountId"] = AccountId ?? (object) DBNull.Value;
			dr["AccessRoleId"] = AccessRoleId ?? (object) DBNull.Value;
			dr["CreatedDate"] = CreatedDate ?? (object) DBNull.Value;
			dr["LastModifiedDate"] = LastModifiedDate ?? (object) DBNull.Value;
			dr["IsDeleted"] = IsDeleted ?? (object) DBNull.Value;

			ds.Tables[TableName].Rows.Add(dr);
		}

		protected void MapFrom(DataRow dr)
		{
			PermissionId = dr["PermissionId"] != DBNull.Value ? Convert.ToInt32(dr["PermissionId"]) : PermissionId = null;
			AccountId = dr["AccountId"] != DBNull.Value ? Convert.ToInt32(dr["AccountId"]) : AccountId = null;
			AccessRoleId = dr["AccessRoleId"] != DBNull.Value ? Convert.ToInt32(dr["AccessRoleId"]) : AccessRoleId = null;
			CreatedDate = dr["CreatedDate"] != DBNull.Value ? Convert.ToDateTime(dr["CreatedDate"]) : CreatedDate = null;
			LastModifiedDate = dr["LastModifiedDate"] != DBNull.Value
			                   	? Convert.ToDateTime(dr["LastModifiedDate"])
			                   	: LastModifiedDate = null;
			IsDeleted = dr["IsDeleted"] != DBNull.Value ? Convert.ToBoolean(dr["IsDeleted"]) : IsDeleted = null;
		}

		private static List<Permission> MapFrom(DataSet ds)
		{
			// Initialise Collection.
			List<Permission> objects = new List<Permission>();

			// Validation.
			if (ds == null)
				throw new ApplicationException("Cannot map to dataset null.");
			
			if (ds.Tables[TableName].Rows.Count == 0)
				return objects;

			if (ds.Tables[TableName] == null)
				throw new ApplicationException("Cannot find table [dbo].[Permission] in DataSet.");

			if (ds.Tables[TableName].Rows.Count < 1)
				throw new ApplicationException("Table [dbo].[Permission] is empty.");

			// Map DataSet to Instance.
			foreach (DataRow dr in ds.Tables[TableName].Rows)
			{
				var instance = new Permission();
				instance.MapFrom(dr);
				objects.Add(instance);
			}

			// Return collection.
			return objects;
		}

		#endregion

		#region CRUD Methods

		public static Permission Get(Int32 permissionId)
		{
			Permission instance = new Permission();

			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspPermission_SELECT";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, permissionId))
			{
				using (DataSet ds = db.ExecuteDataSet(dbCommand))
				{
					if (ds == null || ds.Tables[0].Rows.Count == 0)
						throw new ApplicationException(String.Format("Could not get Permission ID:{0} from Database.", permissionId));
					// Return results.
					ds.Tables[0].TableName = TableName;

					instance.MapFrom(ds.Tables[0].Rows[0]);
				}
			}
			return instance;
		}

		#region INSERT

		private void Insert(Int32? accountId, Int32? accessRoleId, DateTime? createdDate, DateTime? lastModifiedDate,
		                    Boolean? isDeleted, DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspPermission_INSERT";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, accountId, accessRoleId, createdDate, lastModifiedDate, isDeleted))
			{
				PermissionId =
					Convert.ToInt32(transaction == null ? db.ExecuteScalar(dbCommand) : db.ExecuteScalar(dbCommand, transaction));
			}
		}

		/// <summary>
		/// Insert current Permission to database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		private void Insert(DbTransaction transaction = null)
		{
			Insert(AccountId, AccessRoleId, CreatedDate, LastModifiedDate, IsDeleted, transaction);
		}

		#endregion

		#region UPDATE

		private static void Update(Int32? permissionId, Int32? accountId, Int32? accessRoleId, DateTime? createdDate,
		                           DateTime? lastModifiedDate, Boolean? isDeleted, DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspPermission_UPDATE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
			{
				db.DiscoverParameters(dbCommand);
				dbCommand.Parameters["@permissionId"].Value = permissionId;
				dbCommand.Parameters["@accountId"].Value = accountId;
				dbCommand.Parameters["@accessRoleId"].Value = accessRoleId;
				dbCommand.Parameters["@createdDate"].Value = createdDate;
				dbCommand.Parameters["@lastModifiedDate"].Value = lastModifiedDate;
				dbCommand.Parameters["@isDeleted"].Value = isDeleted;

				if (transaction == null)
					db.ExecuteNonQuery(dbCommand);
				else
					db.ExecuteNonQuery(dbCommand, transaction);
			}
		}

		private static void Update(Permission permission)
		{
			permission.Update();
		}

		private static void Update(Permission permission, DbTransaction transaction)
		{
			permission.Update(transaction);
		}

		/// <summary>
		/// Updates changes to the database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		private void Update(DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspPermission_UPDATE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
			{
				db.DiscoverParameters(dbCommand);
				dbCommand.Parameters["@permissionId"].SourceColumn = "PermissionId";
				dbCommand.Parameters["@accountId"].SourceColumn = "AccountId";
				dbCommand.Parameters["@accessRoleId"].SourceColumn = "AccessRoleId";
				dbCommand.Parameters["@createdDate"].SourceColumn = "CreatedDate";
				dbCommand.Parameters["@lastModifiedDate"].SourceColumn = "LastModifiedDate";
				dbCommand.Parameters["@isDeleted"].SourceColumn = "IsDeleted";

				using (DataSet ds = new DataSet())
				{
					MapTo(ds);
					ds.AcceptChanges();
					ds.Tables[0].Rows[0].SetModified();
					if (transaction == null)
						db.UpdateDataSet(ds, TableName, null, dbCommand, null, UpdateBehavior.Standard);
					else
						db.UpdateDataSet(ds, TableName, null, dbCommand, null, transaction);
				}
			}
		}

		#endregion

		#region DELETE

		private static void Delete(Int32? permissionId, DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspPermission_DELETE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, permissionId))
			{
				if (transaction != null)
				{
					db.ExecuteNonQuery(dbCommand, transaction);
				}
				else
				{
					db.ExecuteNonQuery(dbCommand);
				}
			}
		}

		/// <summary>
		/// Delete current Permission from database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		private void Delete(DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspPermission_DELETE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, PermissionId))
			{
				if (transaction != null)
				{
					db.ExecuteNonQuery(dbCommand, transaction);
				}
				else
				{
					db.ExecuteNonQuery(dbCommand);
				}
			}
			PermissionId = null;
		}

		#endregion

		#region SEARCH

		internal static List<Permission> Search(Int32? permissionId = null, Int32? accountId = null, Int32? accessRoleId = null,
		                                       DateTime? createdDate = null, DateTime? lastModifiedDate = null,
		                                       Boolean? isDeleted = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspPermission_SEARCH";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, permissionId, accountId, accessRoleId, createdDate, lastModifiedDate, isDeleted))
			{
				using (DataSet ds = db.ExecuteDataSet(dbCommand))
				{
					ds.Tables[0].TableName = TableName;
					return MapFrom(ds);
				}
			}
		}


		private static List<Permission> Search(Permission searchObject)
		{
			return Search(searchObject.PermissionId, searchObject.AccountId, searchObject.AccessRoleId, searchObject.CreatedDate,
			              searchObject.LastModifiedDate, searchObject.IsDeleted);
		}

		#endregion

		#endregion

		#endregion
	}
}